package com.joker.orange.service;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.joker.common.exception.ServiceException;
import com.joker.oss.core.OssClient;
import com.joker.oss.entity.UploadResult;
import com.joker.oss.factory.OssFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RequiredArgsConstructor
@Service
public class PublicService {

    public String getQrCode(String url, String inviteCode){
        OssClient storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            // 生成二维码
            BufferedImage image = QrCodeUtil.generate(url + "?inviteCode=" + inviteCode, 300, 300);
            // 转换为InputStream
            ByteArrayInputStream inputStream = bufferedImageToInputStream(image);
            uploadResult = storage.uploadSuffix(inputStream, "JPEG", "image/jpeg");
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }
        return uploadResult.getUrl();
    }

    public static ByteArrayInputStream bufferedImageToInputStream(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", baos);
        byte[] imageInByte = baos.toByteArray();
        return new ByteArrayInputStream(imageInByte);
    }

}
